package com.xiaocz.common.widgets.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Build;
import android.view.WindowManager;
import android.widget.TextView;

import com.xiaocz.common.R;

import java.util.Objects;

public class LoadingDialog {

    private AlertDialog ad;
    public TextView textLoading;
    private Context context;

    public LoadingDialog(Context context) {
        ad = new AlertDialog.Builder(context, R.style.MyDialogStyle).create();
        this.context = context;
    }

    public void show(boolean canBack, int view) {
        if (ad != null) {
            ad.setCanceledOnTouchOutside(canBack);// 设置在点击Dialog外是否取消Dialog进度条
            ad.show();
            ad.setContentView(view);
        }
    }

    public void showService(boolean canBack, int view) {
        if (ad != null) {
            ad.setCanceledOnTouchOutside(canBack);// 设置在点击Dialog外是否取消Dialog进度条
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
                Objects.requireNonNull(ad.getWindow()).setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
            } else {
                Objects.requireNonNull(ad.getWindow()).setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            }
            ad.show();
            ad.setContentView(view);
        }
    }

    /**
     * @param canBack 设置在点击Dialog外是否取消Dialog进度条
     * @param loading 显示内容 为空的时候默认 显示<加载中...>
     */
//    public void show(boolean canBack, String loading) {
//        if (ad == null) {
//            ad = new AlertDialog.Builder(context).create();
//            View convertView = LayoutInflater.from(context).inflate(
//                    R.layout.tb_progress, null);
//            ad.setContentView(convertView);
//            textLoading = (TextView) convertView.findViewById(R.id.loading);
//        }
//        ad.setCanceledOnTouchOutside(canBack);// 设置在点击Dialog外是否取消Dialog进度条
//        ad.show();
//        textLoading.setVisibility(View.VISIBLE);
//        textLoading.setText(loading);
//    }

    /**
     * 关闭对话框
     */
    public void dismiss() {
        if (ad != null) {
            try {
                ad.dismiss();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    public void cancel() {
        if (ad != null) {
            ad.cancel();
        }
    }
}
